package com.sgcc.nfc.lock.data.repository

import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.core.network.safeApiCall
import com.sgcc.nfc.lock.core.network.safeApiCallVoid
import com.sgcc.nfc.lock.core.storage.TokenManager
import com.sgcc.nfc.lock.data.remote.api.AuthApi
import com.sgcc.nfc.lock.data.remote.api.LoginRequest
import com.sgcc.nfc.lock.domain.model.LoginResult
import com.sgcc.nfc.lock.domain.model.UserProfile
import com.sgcc.nfc.lock.domain.repository.AuthRepository
import javax.inject.Inject

class AuthRepositoryImpl @Inject constructor(
    private val authApi: AuthApi,
    private val tokenManager: TokenManager
) : AuthRepository {

    override suspend fun login(username: String, password: String): NetworkResult<LoginResult> {
        val result = safeApiCall { authApi.login(LoginRequest(username, password)) }
        return when (result) {
            is NetworkResult.Success -> {
                val loginResult = result.data.toDomain()
                    ?: return NetworkResult.Error(-1, "登录响应异常")
                tokenManager.saveToken(loginResult.token)
                NetworkResult.Success(loginResult)
            }
            is NetworkResult.Error -> result
            NetworkResult.Loading -> NetworkResult.Loading
        }
    }

    override suspend fun logout(): NetworkResult<Unit> {
        val response = safeApiCallVoid { authApi.logout() }
        if (response is NetworkResult.Success) {
            tokenManager.clear()
        }
        return response
    }

    override suspend fun getProfile(): NetworkResult<UserProfile> {
        val result = safeApiCall { authApi.getUserInfo() }
        return when (result) {
            is NetworkResult.Success -> NetworkResult.Success(result.data.toDomain())
            is NetworkResult.Error -> result
            NetworkResult.Loading -> NetworkResult.Loading
        }
    }

    override suspend fun clearToken() {
        tokenManager.clear()
    }
}
